package com.zhentao.dataintegrity.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.dataintegrity.domain.entity.ExecutionRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface ExecutionRecordMapper extends BaseMapper<ExecutionRecord> {

    /**
     * 分页查询执行记录（带任务信息）
     */
    @Select("<script>" +
            "SELECT r.*, t.task_title " +
            "FROM di_execution_record r " +
            "LEFT JOIN di_integrity_task t ON r.task_id = t.id " +
            "WHERE 1=1 " +
            "<if test='taskId != null'> AND r.task_id = #{taskId} </if>" +
            "<if test='executionStatus != null and executionStatus != \"\"'> AND r.execution_status = #{executionStatus} </if>" +
            "<if test='triggerType != null and triggerType != \"\"'> AND r.trigger_type = #{triggerType} </if>" +
            "ORDER BY r.start_time DESC" +
            "</script>")
    IPage<ExecutionRecord> selectPageWithTask(Page<ExecutionRecord> page,
                                            @Param("taskId") Long taskId,
                                            @Param("executionStatus") String executionStatus,
                                            @Param("triggerType") String triggerType);

    /**
     * 根据任务ID查询执行记录
     */
    @Select("SELECT r.*, t.task_title " +
            "FROM di_execution_record r " +
            "LEFT JOIN di_integrity_task t ON r.task_id = t.id " +
            "WHERE r.task_id = #{taskId} " +
            "ORDER BY r.start_time DESC")
    List<ExecutionRecord> selectByTaskId(@Param("taskId") Long taskId);

    /**
     * 根据执行ID查询执行记录
     */
    @Select("SELECT r.*, t.task_title " +
            "FROM di_execution_record r " +
            "LEFT JOIN di_integrity_task t ON r.task_id = t.id " +
            "WHERE r.execution_id = #{executionId}")
    ExecutionRecord selectByExecutionId(@Param("executionId") String executionId);

    /**
     * 更新执行状态
     */
    @Update("UPDATE di_execution_record SET " +
            "execution_status = #{status}, " +
            "end_time = #{endTime}, " +
            "duration_seconds = #{durationSeconds}, " +
            "total_diff_rmb = #{totalDiffRmb}, " +
            "total_diff_usd = #{totalDiffUsd}, " +
            "error_message = #{errorMessage} " +
            "WHERE execution_id = #{executionId}")
    int updateExecutionStatus(@Param("executionId") String executionId,
                            @Param("status") String status,
                            @Param("endTime") LocalDateTime endTime,
                            @Param("durationSeconds") Integer durationSeconds,
                            @Param("totalDiffRmb") BigDecimal totalDiffRmb,
                            @Param("totalDiffUsd") BigDecimal totalDiffUsd,
                            @Param("errorMessage") String errorMessage);

    /**
     * 取消执行
     */
    @Update("UPDATE di_execution_record SET " +
            "execution_status = 'CANCELLED', " +
            "end_time = #{endTime}, " +
            "error_message = '用户取消执行' " +
            "WHERE execution_id = #{executionId} " +
            "AND execution_status = 'RUNNING'")
    int cancelExecution(@Param("executionId") String executionId, @Param("endTime") LocalDateTime endTime);

    /**
     * 查询运行中的执行记录
     */
    @Select("SELECT * FROM di_execution_record " +
            "WHERE execution_status = 'RUNNING' " +
            "ORDER BY start_time DESC")
    List<ExecutionRecord> selectRunningExecutions();

    /**
     * 查询最近的执行记录
     */
    @Select("SELECT r.*, t.task_title " +
            "FROM di_execution_record r " +
            "LEFT JOIN di_integrity_task t ON r.task_id = t.id " +
            "ORDER BY r.start_time DESC " +
            "LIMIT #{limit}")
    List<ExecutionRecord> selectRecentExecutions(@Param("limit") int limit);

    /**
     * 清理历史记录
     */
    @Update("DELETE FROM di_execution_record WHERE created_time < #{beforeDate}")
    int cleanHistoryBefore(@Param("beforeDate") LocalDateTime beforeDate);
}
